const path = require('path');
const url = require('url');
let disconnectTime;
const { exec, spawn } = require('child_process');
//const cors = require('koa2-cors'); // 导入koa2-cors模块


const config = require("./config.json");

config.app_title = config.app_title || 'Open IP-KVM';
config.mjpg_streamer.stream_port = config.mjpg_streamer.stream_port || 8010;

const ws = require('ws');
const Koa = require('koa');
const KoaStaic = require('koa-static');

const { startSerial } = require('./serial.js');
const { startMJPGStreamer } = require('./mjpg-streamer.js');

const cookieSecret = require('../pyserver/config.json');

function closeMjpgStreamer() {

  const cmd = 'pkill -f mjpg_streamer';

  exec(cmd, (err, stdout, stderr) => {

    if(err) {
      console.error('关闭mjpg_streamer失败:', err);
      return;
    }

    console.log('mjpg_streamer已关闭');
    
    // 切换USB模式
//    exec('echo gadget > /sys/kernel/debug/usb/ci_hdrc.0/role');

//    exec('echo host > /sys/kernel/debug/usb/ci_hdrc.0/role'); 

  });

}
// cookie验证中间件  
async function auth(ctx, next) {

  const cookie = ctx.cookies.get('auth_cookie');

  if (cookie !== cookieSecret.cookie_value) {
    ctx.status = 404;
    return;
  }

  await next();
}

async function start() {

  try {
    const writeSerial = startSerial(config.serialport);
    await startMJPGStreamer(config.mjpg_streamer);

    function websocketHandler(ws) {
      console.log('new websocket connection');
      ws.on('message', function message(data) {
        disconnectTime = null;

        const msg = JSON.parse(data.toString());
        switch (msg.type) {
          case 'write_serial':
            writeSerial(msg.payload);
            break;
        }
      });

      ws.send(JSON.stringify({
        type: 'welcome',
        payload: 'Open IP-KVM Server'
      }));
      ws.on('close', () => {
        disconnectTime = Date.now();
      });
    }
    setInterval(() => {
      if(disconnectTime && Date.now() - disconnectTime > 60000) {
        closeMjpgStreamer(); // 关闭子进程

        process.exit();
      }
    }, 10000);

    const app = new Koa();
  //  app.use(cors({
   //   origin: '*', // 允许所有来源的请求，你可以根据需要自定义
   //   methods: ['GET', 'POST', 'PUT', 'DELETE'], // 允许的HTTP方法
   //   allowHeaders: ['Content-Type', 'Authorization'], // 允许的请求头
   // }));

    app.use(KoaStaic(path.join(__dirname, '../public')));
    app.use(auth);

    const server = app.listen(config.listen_port);
    console.log(`listen on ${config.listen_port}...`);

    app.use(async function router(ctx) {
      if (ctx.path === '/api/config') {
        ctx.body = config;
      }
    });

    const wsInstance = new ws.WebSocketServer({ noServer: true });
    server.on('upgrade', function upgrade(request, socket, head) {
      const { pathname } = url.parse(request.url);

      if (pathname === '/websocket') {
        wsInstance.handleUpgrade(request, socket, head, function done(ws) {
          wsInstance.emit('connection', ws, request);
        });
      } else {
        socket.destroy();
      }
    });

    wsInstance.on('connection', websocketHandler);
  } catch(e) {
    console.log(e);
    process.exit(1);
  }

}

start();
